<template>
    <div>
        <el-tabs addable @tab-click="handleTabClick" @tab-add="addTable" v-model="activeTab">
            <template #add-icon>
                <el-icon>
                    <Plus @click="addTable" />
                </el-icon>
            </template>
            <el-tab-pane v-for="(table, index) in tables" :key="index" :label="table.title" :name="table.name">
                <template #label>
                    <span class="custom-tabs-label">
                        <span v-if="!table._editable" @dblclick="editTable(table.table_id)">{{ table.title }}</span>
                    </span>
                </template>
                <el-form :model="table" :rules="rules" :ref="(el) => tbFormRef[table.name] = el">
                    <el-table v-loading="!tables.length" :data="table.columns" empty-text="未添加字段"
                        class="w-100 overflow-auto">
                        <el-table-column prop="title" label="名称" align="center" min-width="120">
                            <template #default="scope">
                                <el-form-item v-if="scope.row._title_editable"
                                    :prop="'columns.' + scope.$index + '.title'" :rules="rules.title"
                                    :show-message="false">
                                    <el-input clearable @input="onTitleChange(scope.row)"
                                        v-model="scope.row.title"></el-input>
                                </el-form-item>

                                <span v-else>{{ scope.row.title }}</span>
                            </template>
                        </el-table-column>
                        <el-table-column prop="name" label="标识" align="center" min-width="120">
                            <template #default="scope">
                                <el-form-item v-if="scope.row._name_edit" :prop="'columns.' + scope.$index + '.name'"
                                    :rules="rules.name" :show-message="false">
                                    <el-input @dblclick="scope.row._name_edit = scope.row.name.length == 0" clearable
                                        v-model="scope.row.name"></el-input>
                                </el-form-item>
                                <span v-if="!scope.row._name_edit"
                                    @dblclick="scope.row._name_edit = scope.row.editable">
                                    {{ scope.row.name ? scope.row.name : '自动生成' }}
                                </span>
                            </template>
                        </el-table-column>
                        <el-table-column prop="is_nullable" label="可空" align="center">
                            <template #default="scope">
                                <el-switch v-model="scope.row.is_nullable"
                                    :disabled="!scope.row._is_nullable_editable"></el-switch>
                            </template>
                        </el-table-column>
                        <el-table-column prop="is_dict_label" label="标签字段" align="center">
                            <template #default="scope">
                                <el-switch v-model="scope.row.is_dict_label"
                                    :disabled="!scope.row._is_dict_label_editable"></el-switch>
                            </template>
                        </el-table-column>
                        <el-table-column prop="is_like_query" label="模糊查询" align="center">
                            <template #default="scope">
                                <el-switch v-model="scope.row.is_like_query"
                                    :disabled="!scope.row._is_like_query_editable"></el-switch>
                            </template>
                        </el-table-column>
                        <el-table-column prop="source" label="数据来源" align="center" min-width="120">
                            <template #default="scope">
                                <el-form-item v-if="scope.row._source_editable"
                                    :prop="'columns.' + scope.$index + '.source'" :rules="rules.source"
                                    :show-message="false">
                                    <el-select placeholder="请选择数据来源" @change="onSourceChange(scope.row, true)"
                                        filterable style="width:80" v-model="scope.row.source">
                                        <el-option v-for="item in $data.enums.getItems('data-source')" :key="item.value"
                                            :label="item.label" :value="item.value">
                                        </el-option>
                                    </el-select>
                                </el-form-item>
                                <span v-if="!scope.row._source_editable">
                                    <el-tag :type="$utils.conv.getTypeColor(scope.row.source)" round>
                                        {{ $data.enums.getName("data-source", scope.row.source) }}
                                    </el-tag>
                                </span>
                            </template>
                        </el-table-column>
                        <el-table-column prop="method" label="构建方法" align="center" min-width="120">
                            <template #default="scope">
                                <el-form-item
                                    v-if="scope.row._method_editable && scope.row._methods && scope.row._methods.length > 0"
                                    :prop="'columns.' + scope.$index + '.method'" :rules="rules.method"
                                    :show-message="false">
                                    <el-select @change="onmethodChange(scope.row, true)" placeholder="请选择来源"
                                        v-model="scope.row.method">
                                        <el-option v-for="item in scope.row._methods" :key="item.value"
                                            :label="item.label" :value="item.value">
                                        </el-option>
                                    </el-select>
                                </el-form-item>
                                <span v-else :class="$utils.conv.getTextColor(scope.row.method)">
                                    {{ $data.enums.getName($data.enums.joinType("data-source", scope.row.source),
                                        scope.row.method) }}
                                </span>
                            </template>
                        </el-table-column>
                        <el-table-column prop="param" label="参数/条件/初始值" align="center" min-width="120">
                            <template #default="scope">
                                <span v-if="scope.row._param_editable">
                                    <el-form-item v-if="$utils.kit.isEqual(scope.row.method, 'auto-increment')"
                                        :prop="'columns.' + scope.$index + '.param'" :rules="rules.param"
                                        :show-message="false">
                                        <el-input-number v-model="scope.row.param" :min="0"></el-input-number>
                                    </el-form-item>
                                    <span v-else-if="$utils.kit.isEqual(scope.row.method, 'data-dict')"
                                        class="d-flex align-items-center justify-content-between">
                                        <el-form-item label="" :prop="'columns.' + scope.$index + '.param1'"
                                            :rules="rules.param" :show-message="false">
                                            <!-- 数据字典的键值 -->
                                            <el-select
                                            v-model="scope.row.param"
                                            clearable
                                            style="width: 100px;"
                                            placeholder="请选择"
                                          >
                                            <el-option
                                              v-for="item in dicts"
                                              :key="item.id"
                                              :label="item.label"
                                              :value="item.id"
                                            />
                                          </el-select>
                                        </el-form-item>
                                    </span>
                                    <span v-else-if="$utils.kit.isEqual(scope.row.source, 'usr:input')"
                                        class="d-flex align-items-center justify-content-between">
                                        <el-form-item label="" :prop="'columns.' + scope.$index + '.param2'"
                                            :rules="rules.param" :show-message="false">
                                            <el-input v-model="scope.row.param" max-length="32" clearable></el-input>
                                        </el-form-item>
                                    </span>

                                    <span v-else-if="$utils.kit.isEqual(scope.row.method, 'data-table')">
                                        <el-form-item :prop="'columns.' + scope.$index + '.param'" :rules="rules.param"
                                            :show-message="false">
                                            <!-- 数据表 -->
                                            <el-select placeholder="请选择" v-model="scope.row.param">
                                                <el-option v-for="item in tables" :key="item.title" :label="item.title"
                                                    :value="item.table_id">
                                                </el-option>
                                            </el-select>
                                        </el-form-item>


                                    </span>
                                    <span v-else-if="$utils.kit.isEqual(scope.row.method, 'CURRENT_TIMESTAMP')">
                                        <el-form-item :prop="'columns.' + scope.$index + '.param'" :rules="rules.param"
                                            :show-message="false">
                                            <el-select placeholder="请选择" v-model="scope.row.param">
                                                <el-option v-for="item in scope.row._params" :key="item.label"
                                                    :label="item.label" :value="item.value">
                                                </el-option>
                                            </el-select>
                                        </el-form-item>

                                    </span>
                                </span>


                                <span v-else>
                                    <span v-if="$utils.kit.isEqual(scope.row.method, 'CURRENT_TIMESTAMP')">
                                        {{ $data.enums.getName($data.enums.joinType('data-source', scope.row.source,
                                            scope.row.method), scope.row.param) }}
                                    </span>
                                <span v-else-if="$utils.kit.isEqual(scope.row.method, 'data-dict')" v-x-dict="scope.row.param">
                                </span>
                                    <span v-else>
                                        {{ scope.row.param }}
                                    </span>


                                </span>
                            </template>

                        </el-table-column>
                        <el-table-column prop="type" label="数据类型" align="center" min-width="140">
                            <template #default="scope">
                                <el-form-item
                                    v-if="scope.row._type_editable && $utils.kit.isEqual(scope.row.source, 'usr:input')"
                                    :prop="'columns.' + scope.$index + '.type'" :rules="rules.type"
                                    :show-message="false">
                                    <el-select placeholder="请选择类型" filterable v-model="scope.row.type">
                                        <el-option v-for="item in $data.enums.getItems('dbType')" :key="item.type"
                                            :label="item.label" :value="item.value">
                                            <span class="float-start">{{ item.label }}</span>
                                            <span class="float-end text-black-50" style="font-size:0.65rem">
                                                {{ item.value }}
                                            </span>
                                        </el-option>
                                    </el-select>
                                </el-form-item>
                                <span v-if="!scope.row._type_editable">
                                    <el-tag :type="$utils.conv.getTypeColor(scope.row.type)" round>
                                        {{ $data.enums.getName("dbType", scope.row.type) }}
                                    </el-tag>
                                </span>
                            </template>
                        </el-table-column>
                        <el-table-column label="操作" width="120" align="center">
                            <template #default="scope">
                                <span>
                                    <el-button link size="mini" type="primary" :icon="Top" />

                                    <el-button v-if="!scope.row.editable" link size="mini" @click="edit(scope.row)"
                                        type="primary">编辑</el-button>
                                    <el-button v-if="!scope.row.editable && !scope.row.is_prefab" link type="info"
                                        size="mini" @click="del(table.columns, scope.row)">删除</el-button>

                                    <el-button v-if="scope.row.editable" link type="success" size="mini"
                                        @click="save(scope.row, table)">保存</el-button>
                                    <el-button v-if="scope.row.editable" link type="warning" size="mini"
                                        @click="cancel(table.columns, scope.row)">取消</el-button>
                                </span>


                            </template>
                        </el-table-column>
                    </el-table>
                </el-form>

                <div class="w-100 d-flex align-items-center justify-content-center mt-3">
                    <i class="iconfont te-i-add fs-4 add" @click="onAdd(table)"></i>
                </div>
            </el-tab-pane>
            <!-- <el-empty v-if="!tables.length" description="没有数据表" /> -->
        </el-tabs>
        <dbcreater ref="createrTb" @create="onCreateTable"></dbcreater>
    </div>
</template>

<script setup>
import { reactive, ref, useAttrs } from 'vue';
import dbcreater from "./db-create.vue"
import $data from "xcore/data";
import $utils from "xcore/utils";
import _ from 'lodash'
const activeTab = ref('0');
const createrTb = ref(null)
let tables = reactive([])

$data.provider.meta.getAllMetaTable().then(res => {
    tables.push(...res)
    if (tables.length > 0)
        activeTab.value = tables[0].name
})

const rules = {
    'title': [{ required: true, trigger: 'blur' }],
    'name': [{ required: true, trigger: 'blur' }],
    'type': [{ required: true, trigger: 'change' }],
    'source': [{ required: true, trigger: 'change' }],
    'method': [{ required: true, trigger: 'change' }],
    'param1': [{ required: true, trigger: 'blur' }],
    'param2': [{ required: false, trigger: 'blur' }],
};

const tbFormRef = ref({});

const edit = (row) => {
    row._data = _.clone(row) // 备份
    swapEditable(row, true)
    onSourceChange(row)
    onmethodChange(row)
}
const fields = ['title', 'type', 'source', 'method', 'param', "is_nullable","is_dict_label","is_like_query"]


//切换是否可编辑
const swapEditable = (row, editable) => {
    row.editable = editable
    if (!row.is_prefab) {
        fields.forEach(field => {
            row[`_${field}_editable`] = editable
        })
    } else {
        row["_title_editable"] = editable
    }
    if (!editable) {
        row["_name_edit"] = false
    }
}


const del = (columns, row) => {
    columns.splice(columns.indexOf(row), 1)
}

const cancel = (columns, row) => {
    if (!row._data) {
        del(columns, row)
        return
    }
    _.merge(row, row._data) // 还原
    delete row._data // 删除备份
    swapEditable(row, false)
}
const save = (formRow, table) => {
    tbFormRef.value[table.name].validate((valid, fields) => {
        if (!valid) return;
        let row = _.clone(formRow)
        row["table_id"] = table.table_id
        $data.provider.meta.setMetaColumn(row).then(res => {
            console.log("成功：", res)
            formRow.column_id = res.column_id
            swapEditable(formRow, false)
        }).catch(err => {
            console.log("失败：", err)
        })
    });
}
const addTable = () => {
    createrTb.value.show()
}
const editTable = (id) => {
    createrTb.value.show(id)
}
const onTitleChange = (row) => {
    if (row._data && row._data.name) {
        return
    }
    let fields = $utils.conv.getFieldName(row.title)
    if (fields.length > 0)
        row.name = fields[0].substring(0, 32)
}

const onSourceChange = (row, clear) => {
    row._methods = $data.enums.getItems($data.enums.joinType('data-source', row.source))
    if (clear) row.method = ""
}
const onmethodChange = (row, clear) => {
    row._params = $data.enums.getItems($data.enums.joinType('data-source', row.source, row.method))
    if (clear) row.param = ""
}
const onCreateTable = (tb) => {
    $data.provider.meta.getAllMetaTable().then(res => {
        tables.length = 0
        tables.push(...res)
        if (tables.length > 0 && tb && tb.name)
            activeTab.value = tb.name
    })

}
const onAdd = (tb) => {
    const newColumn = { title: '', name: '', type: '',is_dict_label:false,is_like_query:false, source: '', method: '', param: '' };

    swapEditable(newColumn, true);

    let foundPk = false; // 标记是否已经找到了is_pk=true的列
    // 遍历列数组，找到插入点
    for (let i = 0; i < tb.columns.length; i++) {
        if (tb.columns[i].is_pk) {
            foundPk = true;// 找到了is_pk=true的列
        }
        if (foundPk && tb.columns[i].is_prefab && !tb.columns[i].is_pk) {
            tb.columns.splice(i, 0, newColumn);
            return;
        }
    }
    if (!foundPk || !tb.columns.some(col => col.is_prefab && !col.is_pk)) {
        tb.columns.push(newColumn);
    }
}


const dicts=ref([]);
$data.provider.meta.getMetaDictByPid(0).then(res => {
    dicts.value=res
})

</script>

<style scoped>
.add:hover {
    color: #409eff;
    cursor: default;
}

:deep(.el-form-item--small) {
    margin-bottom: 0;
}
</style>